var crypto = require('crypto');
var PINGPP = require('pingpp');
var API_KEY = 'sk_live_nn9SyPO8mzHGeP0enP0GSyz1';
var APP_ID = 'app_y1Si1GqvvDaTjfPO';



exports.createPay = function(req,res){
    var payChannel = req.body.payChannel;
    var payAmounts = req.body.amounts;
    var paySubject = req.body.subject;
    var payOrderId = req.body.orderId;
    var isTest = req.body.isTest;
    //开启测试支付
    if(!isTest){
        isTest = '0';
    }
    var payBody = req.body.payBody;
    var payWxOpenId =req.body.wxOpenId;
    var payUserId = req.body.userId;
    if(!payAmounts || !payChannel ||!payOrderId || !payUserId){
        res.send({code:101,message:"获取支付渠道和金额失败"});
        return;
    }
    if(!payBody){
        payBody = "海外购商品";
    }
    if(!paySubject){
        paySubject = '大众品药海外购';
    }
    //初始化额外参数
    var extra = {};
    //设置参数
    var returnHost = '';
    var returnCancelPath = '/order';
    var returnSuccessPath = '/payment/success';
    switch (isTest){
        case '0':
            returnHost = 'seagou.lovepinyao.com';
            break;
        case '1':
            API_KEY = 'sk_test_1afHe1rjfDW1SG0mb9eD4mLS';
            returnHost = 'test.seagou.lovepinyao.com';
            break;
        case '2':
            returnHost = 'koudai.lovepinyao.com';
            returnCancelPath = '/orders';
            returnSuccessPath = '/pay/success';
            break;
        case '3':
            API_KEY = 'sk_test_1afHe1rjfDW1SG0mb9eD4mLS';
            returnHost = 'test.koudai.lovepinyao.com';
            returnCancelPath = '/orders';
            returnSuccessPath = '/pay/success';
            break;
        case '999':
            API_KEY = 'sk_test_1afHe1rjfDW1SG0mb9eD4mLS';
            returnHost = req.body.rHost;
            returnCancelPath = req.body.rCancle;
            returnSuccessPath = req.body.rSuccess;
            break;
        default :
            res.send({code:104,message:"付款类型有误"});
            break;
    }
    console.log(returnHost,returnCancelPath,returnSuccessPath);
    //初始化ping++对象
    var ping = PINGPP(API_KEY);
    ping.setPrivateKeyPath(__dirname + '/../keys/rsa_private_key.pem');
    //根据不同的渠道设置不同的extra参数
    switch (payChannel){
        case 'alipay_wap':
            extra = {
                'success_url': 'http://' + returnHost + returnSuccessPath +'?userId='+payUserId,
                'cancel_url': 'http://' + returnHost + returnCancelPath +'?userId='+payUserId,
                'app_pay':true
            };
            break;
        case 'upacp_wap':
            break;
        case 'wx_pub':
            extra = {
                'open_id':payWxOpenId
            };
            break;
        default :
            extra = {};
            break;
    }
    //生成支付凭证
    ping.charges.create({
        order_no:  payOrderId,// 推荐使用 8-20 位，要求数字或字母，不允许其他字符
        app:       { id: APP_ID },
        channel:   payChannel,// 支付使用的第三方支付渠道取值，请参考：https://www.pingxx.com/api#api-c-new
        amount:    parseInt(payAmounts),//订单总金额, 人民币单位：分（如订单总金额为 1 元，此处请填 100）
        client_ip: '127.0.0.1',// 发起支付请求客户端的 IP 地址，格式为 IPV4，如: 127.0.0.1
        currency:  "cny",
        subject:   paySubject,
        body:      payBody,
        extra:     extra
    }, function(err, charge) {
        if(err){
            console.log(err);
            res.send({code:102,message:err});
        }else{
            //将chargeId写入到订单信息中
            var Order = Parse.Object.extend('OPOrder');
            var order = new Order();
            order.id = payOrderId;
            order.set('chargeId',charge.id);
            order.set('chargeNum',payOrderId);
            order.save().then(function (orderE) {
                res.send({code:200,message:"获取凭证成功",results:charge});
            }, function (err) {
                res.send({code:103,message:"写入charge信息失败"});
            });
        }
    });
};




